﻿using SqlSugar;
using SunnyPaine.Autofac.Extension.SqlSugar.Entities;
using System;
using System.Collections.Generic;
using System.Text;

namespace SunnyPaine.Autofac.Extension.SqlSugar
{
    /// <summary>
    /// 数据库连接管理器。
    /// </summary>
    public static class SqlSugarManager
    {
        /// <summary>
        /// 创建数据库实例。
        /// </summary>
        /// <param name="infos">数据库连接信息，可以多个。</param>
        /// <returns></returns>
        public static SqlSugarScope CreateDBA(List<ConnectionInfo> infos)
        {
            List<ConnectionConfig> configs = new List<ConnectionConfig>();
            foreach (ConnectionInfo info in infos)
            {
                configs.Add(new ConnectionConfig()
                {
                    ConfigId = info.ConfigId,
                    ConnectionString = info.ConnectionString,
                    DbType = info.DbType,
                    InitKeyType = info.InitKeyType,
                    IsAutoCloseConnection = info.IsAutoCloseConnection,
                    MoreSettings = new ConnMoreSettings()
                    {
                        DisableMillisecond = info.DisableNvarchar,
                        TableEnumIsString = info.TableEnumIsString
                    }
                });
            }
            Action<SqlSugarClient> action = new Action<SqlSugarClient>(client =>
            {
                client.Aop.OnLogExecuting = (sql, paras) =>
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine($"****sql => {sql}");
                    foreach (SugarParameter item in paras)
                    {
                        sb.AppendLine($"****parameters => {item.ParameterName} : {item.Value}");
                    }
                    Console.WriteLine(sb.ToString());
                };
                client.Aop.OnError = (error) =>
                {
                    Console.WriteLine(error.Message);
                };
            });
            return new SqlSugarScope(configs, action);
        }
    }
}
